<?php

	/**
	*	Process CSV with Taxamatch
	*	@author Michael Giddens
	*/

	set_time_limit(300);
	ini_set("memory_limit","1000M");
	ini_set('post_max_size', '128M');
	ini_set('upload_max_filesize', '128M');

error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors',1);

	/**
	* auto_detect_line_endings allows for the follow csv formats
	*	1. Comma delimited CSV (*.csv)
	*	2. CSV (MacIntosh) (*.csv)
	*	3. CSV (MS-DOS)
	*/
	ini_set("auto_detect_line_endings", 1);

	require_once('config.php');
	require_once('classes/class.mysqli_database.php');
	require_once('classes/class.taxamatch.php');
	require_once('classes/class.misc.php');
	require_once('classes/class.csv_process.php');
	require_once('classes/class.dwca_process.php');

// 	$folder_path = dirname(__FILE__) . '/';
	$folder_path = '/var/www/html/taxamatch/api/';

	$urlTemplate = 'http://tm.silverbiology.com/taxamatch/api/csv_process/';

	$inputFolder = "";
	$tmpFolder = "csv_process/";
	$fileId = uniqid();

	if(!file_exists($folder_path . $tmpFolder)) mkdir($folder_path . $tmpFolder,0755);

	$allowedExt = array('csv','zip');
	$time_start = microtime_float();
	$type = '';

// echo '<pre>';print_r($_REQUEST);

# if file uploaded
	if(trim($_REQUEST['url']) != '') {
		if(!checkExtension(trim($_REQUEST['url']), $allowedExt)) {
			print json_encode( array( 'success' => false, 'error' => "Error - Input file type not supported. Upload a csv or dwca file." ) );
			exit();
		}
		$ext = getExtension(trim($_REQUEST['url']));
		$input_file = $folder_path . $tmpFolder . $fileId . '.' . $ext;
		if(!downloadRemoteFile($_REQUEST['url'],$input_file)) {
			print json_encode( array( 'success' => false, 'error' => 'Error - ' . getError(103) ) );
			exit();
		}
		$checkFile = $input_file;
	} elseif (isset($_FILES['csv-file']['tmp_name'])) {
		$input_file = $_FILES['csv-file']['tmp_name'];
		$checkFile = $_FILES['csv-file']['name'];
	} elseif( trim($_REQUEST['input'] ) != '') {
		// Files are only allowed to reside in input folder to keep from hacking attemps
		$input_file = $folder_path . $inputFolder . $_REQUEST['input'];
		$input_file = str_replace('../', '', $input_file); // More hack checks
		$checkFile = $input_file;
	} elseif(trim( $_REQUEST['input'] ) == '') {
		print json_encode( array( 'success' => false, 'error' => "Error - Input file cannot be blank. Use argument 'input'." ) );
		exit();
	}

	if(!checkExtension($checkFile, $allowedExt)) {
		print json_encode( array( 'success' => false, 'error' => "Error - Input file type not supported. Upload a csv or dwca file." ) );
		exit();
	}
	$tPathParts = @pathinfo($checkFile);
	$type = @strtolower($tPathParts['extension']);


// $input_file = $folder_path .$tmpFolder . 'occurrence.csv';
	
	$output_file = $_REQUEST['output'] || md5(time()).".csv";
	$source = (isset($_REQUEST['source'])) ? $_REQUEST['source'] : "default";
	$temp_folder_path = $folder_path . $tmpFolder;

	switch ($_REQUEST['cmd']) {
		case 'url':
			// Could extend the code to handle a remote file too.
			break;

		case 'download':
			if ( trim( $output_file ) != '' && file_exists($input_file) ) {

				if ( trim( $output_file ) == '' ) {
					print json_encode( array('success' => false, 'error' => "Error - Output file cannot be blank. Use argument 'output'." ) );
				} else {
					if($type == 'csv') {
						$csv_process = new CSVProcess();
						$csv_process->set('source', $source);
						$csv_process->set('input_file', $input_file);
						$tmp_file = $temp_folder_path . md5( @mktime() ) . ".csv";
						$csv_process->set('output_file', $tmp_file);
						$csv_process->process();

						header('Content-type: application/json');
						print json_encode( array('success' => true, 'url' => $urlTemplate . basename($tmp_file) ) );

/*						$csv_process->download_file();
						@unlink($tmp_file);
						exit();
*/
					} else {
						$db = select_source($source);
						$dwca = new DwcaProcess($db);
						$dwca->set('sourcePath',$input_file);
						$dwca->set('metaFilePath',$folder_path . $tmpFolder);
						$dwca->set('output_file', md5( @mktime() ) . ".csv");
						if($dwca->extractMetaFile()) {
							$dwca->getMetaFile();
							if(!$dwca->processCoreFile()) {
								print json_encode( array( 'success' => false, 'error' => 'Error - ' . getError(105) ) );
								exit();
							}
							header('Content-type: application/json');
							print json_encode( array('success' => true, 'url' => $urlTemplate . basename($dwca->get('output_file')) ) );
/*							$dwca->downloadFile();
							@unlink($tmp_file);
							exit();*/
						} else {
							print json_encode( array( 'success' => false, 'error' => 'Error - ' . getError(104) ) );
							exit();
						}
					}
				}
				
			} else {
				print json_encode( array('success' => false, 'error' => "Error - Not a valid input file or file does not exist." ) );
				exit();
			}
			break;
			
		case 'file':
		
			$output_file = $_REQUEST['output'];
			
			if ( trim( $output_file ) != '' && file_exists($input_file) ) {
			
				if ( trim( $output_file ) == '' ) {
					print "Error - Output file cannot be blank. Use argument 'output'. ";
				} else {
					$csv_process = new CSVProcess();
					$csv_process->set('source', $source);
					$csv_process->set('input_file', $input_file);
					$csv_process->set('output_file', $temp_folder_path . $output_file);
					$csv_process->process();
				}
			} else {
				print "Error - Not a valid input file.";
			}
			break;

		default:
			print "Error - Not a valid command.";
			break;
			
	}
	
	function microtime_float() {
			list($usec, $sec) = explode(" ", microtime());
			return ((float)$usec + (float)$sec);
	}

	function checkExtension($path,$allowedExt) {
		$tExt = getExtension($path);
		return (!in_array($tExt, $allowedExt)) ? false : true;
	}

	function getExtension($path) {
		$tPathParts = @pathinfo($path);
		return $tPathParts['extension'];
	}


	$time_end = microtime_float();
	$time = $time_end - $time_start;

/*	print "Exec duration: $time<br>";
	print round( memory_get_usage() * 0.0009) . "KB<br>";*/
	
?>